package com.ruoyi.whzj.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.whzj.domain.*;
import com.ruoyi.whzj.service.*;
import javafx.concurrent.Task;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.*;


/**
 * 任务控制器
 */
@Controller
@RequestMapping(value = "/phone/whzj/whTask")
public class WhTaskPhoneController extends BaseController {

    @Autowired
    private IWhUserService whUserService;

    @Autowired
    private IWhTaskService whTaskService;

    @Autowired
    private IWhTasksettingService whTasksettingService;

    @Autowired
    private IWhIntegralHistoryService whIntegralHistoryService;

    @Autowired
    private IWhTaskUserService whTaskUserService;

    @Autowired
    private IWhTaskcomplaintService whTaskcomplaintService;

    @Autowired
    private IWhMemberlevelService whMemberlevelService;

    /**
     * 获取用户积分以及任务最小发布量，需要积分
     * @param userId
     * @param type 1点赞，2评论，3关注 4播放
     * @return
     */
    @RequestMapping("/getUserIntegral")
    @ResponseBody
    public AjaxResult getUserIntegral(String userId, String type)throws Exception
    {
        WhUser user = whUserService.selectWhUserById(userId);
        int integral = user.getIntegral();
        WhMemberlevel level = whMemberlevelService.selectWhMemberlevelById(user.getLevel());
        WhTasksetting whTasksetting = whTasksettingService.selectWhTasksettingById("1");

        int minnum = 0;
        int consume = 0;
        int speed = 0;
        Double top = 0.00;
        switch (type){
            case "1":
                minnum = whTasksetting.getGreatMinnum();
                consume = whTasksetting.getGreatConsume();
                speed = whTasksetting.getGreatSpeedone();
                break;
            case "2":
                minnum = whTasksetting.getCommentMinnum();
                consume = whTasksetting.getCommentConsume();
                speed = whTasksetting.getCommentSpeedone();
                break;
            case "3":
                minnum = whTasksetting.getAttentionMinnum();
                consume = whTasksetting.getAttentionConsume();
                speed = whTasksetting.getAttentionSpeedone();
                break;
            case "4":
                minnum = whTasksetting.getPlayMinnum();
                consume = whTasksetting.getPlayConsume();
                break;
        }
        top = (100 - level.getTopDiscount().doubleValue()) * 0.01;
        Map<String, Object> map = new HashMap<>();
        map.put("integral", integral);
        map.put("levelName", user.getLevelName());
        map.put("minnum", minnum);
        map.put("consume", consume);
        map.put("speed", speed);
        map.put("top", top);
        //BigDecimal discount = new BigDecimal((level.getTopDiscount().doubleValue() * 0.01)).setScale(2, BigDecimal.ROUND_HALF_UP);
        map.put("discount", level.getTopDiscount().doubleValue());

        return success("操作成功", map);

    }

    /**
     * 获取任务设置
     * @return
     */
    @RequestMapping("/getTaskSetting")
    @ResponseBody
    public AjaxResult getTaskSetting()throws Exception
    {
        WhTasksetting whTasksetting = whTasksettingService.selectWhTasksettingById("1");
        return success("操作成功", whTasksetting);

    }


    /**
     * 新增任务
     * @param userId
     * @param type 点赞，评论，关注 播放
     * @param workId
     * @param imgUrl
     * @param videoUrl
     * @param allNum
     * @param speed
     * @return
     * @throws Exception
     */
    @RequestMapping("/saveTask")
    @ResponseBody
    public AjaxResult saveTask(String userId, String type, String workId, String imgUrl, String videoUrl,
                               Integer allNum, String speed, String integral, String comments)throws Exception
    {
        WhUser user = whUserService.selectWhUserById(userId);
        if("0".equals(user.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }

        if(user != null){
            if(user.getIntegral() >= Integer.valueOf(integral)){
                WhTask task = new WhTask();
                task.setId(IdWorker.getId());
                task.setCreateTime(new Date());
                task.setUpdateTime(new Date());
                task.setUserId(userId);
                task.setWorkId(workId);
                task.setType(type);
                task.setImgUrl(imgUrl);
                task.setVideoUrl(videoUrl);
                task.setAllNum(allNum);
                task.setNum(0);
                task.setStatus("进行中");
                task.setSpeed(speed);
                task.setComments(comments);

                whTaskService.insertWhTask(task);

                WhUser user1 = new WhUser();
                user1.setId(userId);
                user1.setIntegral(user.getIntegral() - Integer.valueOf(integral));
                whUserService.updateWhUser(user1);

                WhIntegralHistory history = new WhIntegralHistory();
                history.setId(IdWorker.getId());
                history.setCreateTime(new Date());
                history.setUserId(userId);
                history.setIntegral(-Integer.valueOf(integral));
                history.setEventId(task.getId());
                switch (type){
                    case "点赞":
                        history.setOperat("4");
                        break;
                    case "评论":
                        history.setOperat("5");
                        break;
                    case "关注":
                        history.setOperat("6");
                        break;
                    case "播放":
                        history.setOperat("7");

                        WhTask whTask = whTaskService.selectWhTaskById(task.getId());
                        //获取任务配置参数
                        WhTasksetting whTasksetting = whTasksettingService.selectWhTasksettingById("1");
                        String taskUrl = whTasksetting.getPlayApi();
                        String taskParam = whTasksetting.getPlayPara();
                        //执行下单
                        Map<String,String> paramMap = new HashMap<>();
                        String[] parseStr = taskParam.split("&");
                        for(int i=0;i<parseStr.length;i++){
                            String[] temp = parseStr[i].split("=");
                            if("ksid".equals(temp[0])){
                                paramMap.put(temp[0],whTask.getUserId());
                            }else if("zpid".equals(temp[0])){
                                paramMap.put(temp[0],whTask.getWorkId());
                            }else if("need_num_0".equals(temp[0])){
                                paramMap.put(temp[0],whTask.getAllNum().toString());
                            }else{
                                paramMap.put(temp[0],temp[1]);
                            }
                        }
                        String resultStr = OkHttpUtil.postFormParams(taskUrl,paramMap);
                        System.out.println(resultStr);
                        if(resultStr.indexOf("order_id")>0){
                            String[] returnStr = resultStr.split(",");
                            for(int i=0;i<returnStr.length;i++){
                                String[] tempin = returnStr[i].split(":");
                                if("\"order_id\"".equals(tempin[0])){
                                    System.out.println("order_id++++++++"+tempin[1]);
                                    whTask.setTaskOrder(tempin[1].replace("\"",""));
                                    whTaskService.updateWhTask(whTask);
                                }
                            }
                        }

                        break;
                }

                whIntegralHistoryService.insertWhIntegralHistory(history);



                return success("提交成功");

            }else{
                return error("用户积分不足");
            }
        }else{
            return error("用户不存在");
        }

    }


    /**
     * 获取最靠前的一个任务
     * @param type 点赞，评论，关注
     * @return
     * @throws Exception
     */
    @RequestMapping("/getWhTaskOnce")
    @ResponseBody
    public AjaxResult getWhTaskOnce(String userId, String type)throws Exception
    {
        WhUser user = whUserService.selectWhUserById(userId);
        if("0".equals(user.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }

        WhTask task = whTaskService.getWhTaskOnce(type, userId);
        if(task != null){
            if("评论".equals(type)){
                String comments = task.getComments();
                if(EmptyUtils.isNotEmpty(comments)){
                   String[] _commonts = comments.split(",");
                   int index = (int) (Math.random() * _commonts.length);
                   String random = _commonts[index];
                    while (EmptyUtils.isEmpty(random)){
                        random = _commonts[index];
                    }
                   task.setComments(random);
                }
            }
            return success("获取成功", task);
        }
        return error("当前没有新任务，请稍后再试");



    }


    /**
     * 登陆获取任务
     * @return
     * @throws Exception
     */
    @RequestMapping("/getWhTaskLogin")
    @ResponseBody
    public AjaxResult getWhTaskLogin(String number)throws Exception
    {
        number=number.trim();
        WhUser whUser = whUserService.selectWhUserByKuaiId(number);
        if(whUser == null){
            whUser = whUserService.selectWhUserByKuaiNumber(number);
        }
        String userId = "1";
        if(whUser != null){
            userId = whUser.getId();
        }
        WhTask taskOnce = whTaskService.getWhTaskOnce("点赞", userId);
        if(taskOnce != null){
            String workId = taskOnce.getWorkId();
            String url = "http://47.94.111.161:9106/api/v1/kuaishou/user/photos/info?token=0f400461-227b-45bc-98d2-bbdabb3f&photoIds="+workId;
            String json = OkHttpUtil.get(url);
            JSONObject jsonObject = JSONObject.fromObject(json);
            Map<String, Object>  data = ( Map<String, Object>)jsonObject.get("data");
            Map<String, Object>  photos = ( Map<String, Object>) data.get("photos");
            Map<String, Object>  work = ( Map<String, Object>) photos.get(workId);
            Integer likeNum = (int) work.get("like_count");

            WhTask whTask = new WhTask();
            whTask.setId(taskOnce.getId());
            whTask.setLikeNum(likeNum);
            whTaskService.updateWhTask(whTask);

            return success("获取成功", taskOnce);
        }

        List<WhTask> list = new ArrayList<>();
        if(whUser != null){
            list = whTaskService.getWhTaskLogin(whUser.getId());
        }
        if(list.size() == 0){
            list = whTaskService.getWhTaskLoginAll();
        }
        int i = (int) (Math.random() * list.size());
        WhTask task = list.get(i);

        String workId = task.getWorkId();
        String url = "http://47.94.111.161:9106/api/v1/kuaishou/user/photos/info?token=0f400461-227b-45bc-98d2-bbdabb3f&photoIds="+workId;
        String json = OkHttpUtil.get(url);
        JSONObject jsonObject = JSONObject.fromObject(json);
        Map<String, Object>  data = ( Map<String, Object>)jsonObject.get("data");
        Map<String, Object>  photos = ( Map<String, Object>) data.get("photos");
        Map<String, Object>  work = ( Map<String, Object>) photos.get(workId);
        Integer likeNum = (int) work.get("like_count");

        WhTask whTask = new WhTask();
        whTask.setId(task.getId());
        whTask.setLikeNum(likeNum);
        whTaskService.updateWhTask(whTask);


        return success("获取成功", task);

    }


    /**
     * 获取我的任务
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getMyTask")
    @ResponseBody
    public AjaxResult getMyTask(String userId)throws Exception
    {
        WhUser user = whUserService.selectWhUserById(userId);
        if("0".equals(user.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }

        WhTask task = new WhTask();
        task.setUserId(userId);
        return success("获取成功", whTaskService.selectWhTaskListNotVip(task));

    }

    /**
     * 获取我VIP的任务
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getMyVipTask")
    @ResponseBody
    public AjaxResult getMyVipTask(String userId)throws Exception
    {
        WhUser user = whUserService.selectWhUserById(userId);
        if("0".equals(user.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }

        WhTask task = new WhTask();
        task.setUserId(userId);
        task.setType("播放");
        return success("获取成功", whTaskService.selectWhTaskList(task));

    }


    /**
     * 获取置顶需要的积分
     * @param type
     * @return
     * @throws Exception
     */
    @RequestMapping("/getSpeed")
    @ResponseBody
    public AjaxResult getSpeed(String userId, String type)throws Exception
    {
        WhUser user = whUserService.selectWhUserById(userId);
        int integral = user.getIntegral();
        WhTasksetting whTasksetting = whTasksettingService.selectWhTasksettingById("1");
        int speed = 0;
        switch (type){
            case "1":
                speed = whTasksetting.getGreatSpeed();
                break;
            case "2":
                speed = whTasksetting.getCommentSpeed();
                break;
            case "3":
                speed = whTasksetting.getAttentionSpeed();
                break;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("speed", speed);
        map.put("integral", integral);
        map.put("top", user.getToptimes());
        return success("操作成功", map);
    }

    /**
     * 任务置顶
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/taskTop")
    @ResponseBody
    public AjaxResult taskTop(String id, String userId, Integer integral)throws Exception
    {

        WhUser user = whUserService.selectWhUserById(userId);
        int top = user.getToptimes();
        if(top > 0){
            WhUser user1 = new WhUser();
            user1.setId(userId);
            user1.setToptimes(top - 1);
            whUserService.updateWhUser(user1);

            WhTask task = new WhTask();
            task.setId(id);
            task.setIsTop("1");
            whTaskService.updateWhTask(task);

            return success("操作成功");
        }
        if(user.getIntegral() >= Integer.valueOf(integral)) {

            WhUser user1 = new WhUser();
            user1.setId(userId);
            user1.setIntegral(user.getIntegral() - Integer.valueOf(integral));
            whUserService.updateWhUser(user1);

            WhIntegralHistory history = new WhIntegralHistory();
            history.setId(IdWorker.getId());
            history.setCreateTime(new Date());
            history.setUserId(userId);
            history.setIntegral(-Integer.valueOf(integral));
            history.setEventId(id);
            history.setOperat("18");

            WhTask task = new WhTask();
            task.setId(id);
            task.setIsTop("1");
            whTaskService.updateWhTask(task);

            whIntegralHistoryService.insertWhIntegralHistory(history);
            return success("操作成功");
        }
        return error("操作失败");

    }

    /**
     * 获取任务评论内容
     * @param taskId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getTaskContent")
    @ResponseBody
    public AjaxResult getTaskContent(String taskId)throws Exception
    {
        WhTaskUser taskUser = new WhTaskUser();
        taskUser.setTaskId(taskId);
        return success("获取成功", whTaskUserService.selectWhTaskUserList(taskUser));

    }


    /**
     * 评论投诉
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/saveComplaint")
    @ResponseBody
    public AjaxResult saveComplaint(String id)throws Exception
    {
        WhTaskUser taskUser = whTaskUserService.selectWhTaskUserById(id);
        taskUser.setIscomplaint("1");
        whTaskUserService.updateWhTaskUser(taskUser);

        WhTaskcomplaint complaint = new WhTaskcomplaint();
        complaint.setId(IdWorker.getId());
        complaint.setTaskContent(taskUser.getContent());
        complaint.setTaskId(taskUser.getTaskId());
        complaint.setUserId(taskUser.getUserId());
        complaint.setTuid(id);
        complaint.setDealStatus("投诉等待处理");
        whTaskcomplaintService.insertWhTaskcomplaint(complaint);

        return success("投诉成功");

    }
}

